package com.ai.sml.util;

import java.io.IOException;
import java.io.InputStream;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.ai.sml.util.Constants;

/**
 * 发送的请求工具类
 * 
 * @author visen
 * @mail visen1118@gmail.com
 *
 */
public class HttpUtil
{
	private static final Logger log = Logger.getLogger(HttpUtil.class);
	
	public static void responseToClient(String result) throws IOException {
		ServletActionContext.getResponse().setContentType("applicatin/json;charset=utf-8");
		ServletActionContext.getResponse().setHeader("Cache-Control", "no-cache");
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		ServletActionContext.getResponse().getWriter().print(result);
	}

	/** 
	 * @Title:        postData 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param url 短信平台url
	 * @param:        @param msg
	 * @param:        @return
	 * @param:        @throws Exception    
	 * @return:       String    
	 * @throws 
	 * @author        wangxj
	 * @Date          2016年2月15日 下午3:56:38 
	 * Apikey=***************&Username=************&Billid=15838222338&Rspid=1054&InfoMap={"date_time":"2015年11月13日9时49分","txt_fee":"11元"}'
	 */
	public static String postData(String msg) throws MyOwnRuntimeException {
		String result = null;
		PostMethod method = null;
		try {
			assertMsgNotNull(msg);

			long begin = System.currentTimeMillis();
			log.debug("发送请求,开始:==>>" + msg);
			HttpClient client = new HttpClient();
			method = new PostMethod(Constants.SMS_SEND_PARA.urlString);
			StringRequestEntity entity = new StringRequestEntity(fillAssertMsg(msg), "application/json", "utf-8");
			method.setRequestEntity(entity);
			client.executeMethod(method);
			log.debug("准备发送目标URL为:" + method.getURI());

			InputStream in = method.getResponseBodyAsStream();
			result = IOUtils.toString(in, "utf-8");
			IOUtils.closeQuietly(in);

			int statu_code = method.getStatusLine().getStatusCode();

			log.debug("响应报文为：" + result);
			log.debug("发送请求,完成,耗时:" + DateOper.formatDuring2(System.currentTimeMillis() - begin));

			assertResultSuccess(statu_code);
			
			return assertResult(result);

		} catch (Exception e) {
			log.error("对端接口发送失败！", e);
			throw new MyOwnRuntimeException(e);
		} finally {
			if (method != null) {
				method.releaseConnection();
			}
		}
		//return result;
	}

	private static void assertMsgNotNull(String msg) throws MyOwnRuntimeException {
		if (StringUtils.isBlank(msg)) {
			log.warn("待发送的报文为空，请核实！");
			throw new MyOwnRuntimeException("待发送的报文为空，请核实！");
		}
	}
	
	private static void checkAssertMsg(String msg) throws MyOwnRuntimeException {
		if(msg.indexOf("Billid")==-1){
			log.warn("待发送短信手机号码为空，请核实！");
			throw new MyOwnRuntimeException("待发送短信手机号码为空，请核实！");
		}
		if(msg.indexOf("Rspid")==-1){
			log.warn("待发送短信模板标示为空，请核实！");
			throw new MyOwnRuntimeException("待发送短信模板标示为空，请核实！");
		}
		if(msg.indexOf("InfoMap")==-1){
			log.warn("待发送短信内容为空，请核实！");
			throw new MyOwnRuntimeException("待发送短信内容为空，请核实！");
		}
	}
	
	private static String fillAssertMsg(String msg) throws MyOwnRuntimeException {
		StringBuilder msgBuffer = new StringBuilder();
		msgBuffer = msgBuffer.append("Apikey=").append(Constants.SMS_SEND_PARA.Apikey).append("&");
		msgBuffer = msgBuffer.append("Username=").append(Constants.SMS_SEND_PARA.Username).append("&").append(msg);
		return msgBuffer.toString();
	}

	private static void assertResultSuccess(int statu_code) throws MyOwnRuntimeException {
		if (statu_code == 200 || statu_code == 204) {
		} else {
			log.error("调用对端接口响应错误,响应码为" + statu_code);
			throw new MyOwnRuntimeException("调用对端接口响应错误,响应码为" + statu_code);
		}
	}
	
	private static String assertResult(String msg) {
		//默认返回的信息必须包含Returncode和returnmessage，不进行参数的判断
		JSONObject jsonobj = JSONObject.fromObject(msg);
		String returnCode = jsonobj.getString("Returncode");
		String returnmessage = jsonobj.getString("Returnmessage");
		log.info("msg  returnCode= "+returnCode);
		if(Constants.SMS_SEND_PARA.retCode_200.equals(returnCode)){
			return Constants.SMS_SEND_PARA.retSuccString;
		}
		return returnmessage;
	}
	
	public static void main(String[] args) throws Exception{
		HttpUtil httpUtil = new HttpUtil();
		String msg = "Billid=15838222338&Rspid=1054&InfoMap={\"date_time\":\"2015年11月13日9时49分\",\"txt_fee\":\"11元\"}";
		httpUtil.checkAssertMsg(msg);
		System.out.println(httpUtil.fillAssertMsg(msg));
		
		String result= "{\"Returncode\":\"200\",\"Returnmessage\":\"接口调用成功\"}";
		
		//httpUtil.postData(msg);
		System.out.println(httpUtil.assertResult(result));
	}
}
